package com.qkjia.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SelectorDemo1 {

    public static void main(String[] args) throws IOException {
        // 创建selecotr
        Selector selector = Selector.open();

        // 通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 非阻塞
        serverSocketChannel.configureBlocking(false);

        // 绑定连接
        serverSocketChannel.bind(new InetSocketAddress(9999));

        // 将通道注册到选择器上
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 查询已经就绪通道操作
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        // 遍历集合
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while(iterator.hasNext()) {
            SelectionKey key = iterator.next();
            // 判断key就绪状态操作
            if(key.isAcceptable()) {
                // a connection was accepted by a ServerSocketChannel.

                // 测试此键的通道是否已完成或未能完成其套接字连接操作。
            } else if (key.isConnectable()) {

                // a connection was established with a remote server.

                // 测试此密钥的通道是否已准备好读取。
            } else if (key.isReadable()) {

                // a channel is ready for reading

                // 测试此密钥的通道是否已准备好写入
            } else if (key.isWritable()) {

                // a channel is ready for writing

            }
            // 从底层集合中移除此迭代器返回的最后一个元素（可选操作）。
            iterator.remove();
        }


    }
}
